package com.atguigu.crowd.util;

import com.aliyun.api.gateway.demo.util.HttpUtils;
import com.atguigu.crowd.constant.CrowdConstant;
import org.apache.http.HttpResponse;
import org.apache.http.ProtocolVersion;
import org.apache.http.StatusLine;
import org.apache.http.util.EntityUtils;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 通用工具类
 */
public class CrowdUtil {

//    private Logger logger = LoggerFactory.getLogger(CrowdUtil.class);


    /**
     * 通过点三方短信API发送短信
     * @param mobile 接收短信的手机号
     * @param host 短信接口调用的URL地址
     * @param path 发送短信的具体地址
     * @param appcode 调用第三方API的appCode
     * @param smsSignId 签名编号
     * @param templateId 模板编号
     * @return 调用结果是否成功
     */
    public static ResultEntity<String> sendShortMessage(
            String mobile,
            String host,
            String path,
            String method,
            String appcode,
            String smsSignId,
            String templateId) {
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        // 生成验证码
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            int j = ThreadLocalRandom.current().nextInt(10);
            sb.append(j);
        }
        String code = sb.toString();
        querys.put("mobile", mobile);
        querys.put("param", "**code**:" + code + ",**minute**:5");
        querys.put("smsSignId", smsSignId);
        querys.put("templateId", templateId);
        Map<String, String> bodys = new HashMap<String, String>();

        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());
            StatusLine statusLine = response.getStatusLine();
            ProtocolVersion protocolVersion = statusLine.getProtocolVersion();
            int statusCode = statusLine.getStatusCode();
            String reasonPhrase = statusLine.getReasonPhrase();
            //获取response的body
            System.out.println(EntityUtils.toString(response.getEntity()));
            if (statusCode == 200) {
                // 操作成功，把生成的验证码返回
                return ResultEntity.successWithData(code);
            }
            return ResultEntity.failed(reasonPhrase);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.failed(e.getMessage());
        }
    }

//    /**
//     * 判断当前请求是否为Ajax请求
//     * @param request 请求对象
//     * @return true：是Ajax请求；false：不是Ajax请求
//     */
//    public static boolean judgeRequestType(HttpServletRequest request) {
//        // 1.获取请求头
//        String accept = request.getHeader("Accept");
//        String xRequestedWith = request.getHeader("X-Requested-With");
//        String hh = request.getHeader("hh");
//        // 2.判断
//        return (accept != null && accept.contains("application/json"))
//                ||
//                (xRequestedWith != null && "XMLHttpRequest".equals(xRequestedWith));
//    }

    /**
     * 对明文字符串进行MD5加密
     * @param source 明文字符串
     * @return 加密结果
     */
    public static String md5(String source) {
        if (source == null || source.length() == 0) {
            throw new RuntimeException(CrowdConstant.MESSAGE_STRING_INVALIDATE);
        }
        // 加密
        String algorithm = "md5";
        try {
            // 创建messageDigest对象
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
            // 获取明文字符串对应的字节数组
            byte[] input = source.getBytes();
            // 执行加密
            byte[] output = messageDigest.digest(input);
            // 通过bigInteger转为字符串
            int signum = 1;
            // 创建bigInteger对象
            BigInteger bigInteger = new BigInteger(signum, output);
            int radix = 16;
            String encoded = bigInteger.toString(radix).toUpperCase();
            return encoded;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
}
